package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //1.健壮性校验
        if (StringUtils.isEmpty(dto.getName()) && StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }
        //2.查询用户
        WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
        if (ObjectUtils.isEmpty(wmUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        //3.校验密码
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), wmUser.getPassword());
        if (!checkpw) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码为空");
        }
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("user", wmUser);
        resultMap.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));

        return ResponseResult.okResult(resultMap);
    }

//// 1.健壮性校验
//        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
//            log.error("自媒体端登录失败！参数为空");
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码为空");
//        }
//
//// 2.查询用户
//        WmUser user = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
//        if (ObjectUtil.isEmpty(user)) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户不存在");
//        }
//
//// 3.比对密码
//        boolean checkpw = BCrypt.checkpw(dto.getPassword(), user.getPassword());
//        if (!checkpw) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码为空");
//        }
//        user.setPassword(null);
//
//        Map<String, Object> resultMap = new HashMap();
//        resultMap.put("user", user);
//        resultMap.put("token", AppJwtUtil.getToken(Long.valueOf(user.getId())));
//
//        return ResponseResult.okResult(resultMap);
//    }
}